package com.lzy.business.controller.approval;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.github.pagehelper.PageInfo;
import com.lzy.approval.apis.EventServiceApi;
import com.lzy.approval.apis.OnTaskListener;
import com.lzy.approval.apis.TaskServiceApi;
import com.lzy.approval.dtos.EventDto;
import com.lzy.approval.dtos.TaskDto;
import com.lzy.base.apis.SysResourceServiceApi;
import com.lzy.base.dtos.SysResourceDto;
import com.lzy.business.controller.BaseController;
import com.lzy.business.request.PlayProjectRequest;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.product.apis.ProductInfoServiceApi;
import com.lzy.product.common.util.UserUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 流程审批
 */
@Controller
@RequestMapping("/admin/process")
public class ProcessController extends BaseController {

    @Autowired
    private TaskServiceApi taskServiceApi;
    @Autowired
    private SysResourceServiceApi sysResourceServiceApi;
    @Autowired
    private EventServiceApi eventServiceApi;
    @Autowired
    private ProductInfoServiceApi productInfoServiceApi;

//    @RequiresPermissions("sys:process:view")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model) {
        PageInfo<EventDto> pageInfo = eventServiceApi.queryEventList(new Pager(1, Integer.MAX_VALUE, 0L), new EventDto());
        if(null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
            model.addAttribute("eventList", pageInfo.getList());
        }
        model.addAttribute("userId", Long.toString(UserUtil.getCurrentUser().getId()));
        return "approval/process_list";
    }

    /**
     * 数据查询
     * @param userId            用户Id
     * @param auditEventId      审核事件Id
     * @param status            审核状态（0：未审核 1：已审核，未通过 2：已通过）
     * @param applicantName     申请人名称（模糊搜索）
     * @param processAssigneeName   流程经办人
     * @return                  分页数据
     */
//    @RequiresPermissions("sys:process:view")
    @RequestMapping(value = "json", method = RequestMethod.GET)
    @ResponseBody
    public PageBean json(PlayProjectRequest request, String userId, Long auditEventId, Integer status, String applicantName, String processAssigneeName) {
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        PageInfo<TaskDto> pageInfo = taskServiceApi.taskQuery(pager, userId, auditEventId, status, applicantName, processAssigneeName);
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 转向流程审批的查看页面
     * @param model
     * @param id
     * @return
     */
//    @RequiresPermissions("sys:process:detail")
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        TaskDto entity = taskServiceApi.findById(id);
        List<TaskDto> taskList = taskServiceApi.findList(entity.getProcessInstanceId(), null);
        model.addAttribute("taskList", taskList);
        model.addAttribute("entity", entity);
        model.addAttribute("action", "audit");
        return "approval/process_view";
    }

    /**
     * 审核
     * @param id        任务Id
     * @param status    审核状态（1：已通过 2：未通过）
     * @return
     */
    @RequestMapping(value = "auditTask", method = RequestMethod.POST)
    @ResponseBody
    public Result selectTask(String id,Integer status){
        TaskDto taskDto = taskServiceApi.findLastTask(id,status);
        return new Result(taskDto);
    }

    /**
     * 审核
     * @param id        任务Id
     * @param status    审核状态（0：未审核 1：已通过 2：未通过）
     * @param remark    审核备注
     * @return
     */
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    @ResponseBody
    public Result audit(String id, Integer status, String remark) {
        Long assigneeId = UserUtil.getCurrentUser().getId();
        String assigneeName = UserUtil.getCurrentUser().getLoginName();
        taskServiceApi.taskComplete(id, assigneeId, assigneeName, status, remark, new OnTaskListener() {
            @Override
            public void onTaskComplete(String applyId,Long auditEventId, String businessKey, int status, Long userId, String userName, String remark) {
                SysResourceDto sysResourceDto = sysResourceServiceApi.findByEventId(auditEventId);
                        // 资源编码
                        String code = sysResourceDto.getCode();
                        if(null == sysResourceDto || StringUtils.isBlank(code)) {
                            return;
                        }

                        switch (code){
                            case "sys:product:add":
                            case "sys:product:update":{
                                // 产品管理-审核
                        Long applicantId = UserUtil.getCurrentUser().getId();
                        productInfoServiceApi.updateVerifyStatusById(Long.parseLong(businessKey),status,userId,userName,remark,applicantId);
                        break;
                    }
                    default:
                }
            }
        });
        return new Result();
    }

}
